package com.jzz.eletuanbackend.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class TokenValidator {
    public static final String TOKEN_PREFIX = "elt-";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TokenGenerator tokenGenerator;

    public String getValidAccessToken(String userId) {
        return tokenGenerator.getValidAccessToken(userId);
    }

    public String getTokenUId(String token) {
        if (token == null || !token.matches("[0-9a-zA-Z]+") || !stringRedisTemplate.hasKey(token)) {
            return "";
        }
        // 通过双向绑定获取到用户信息
        String uid = stringRedisTemplate.opsForValue().get(token);
        try {
            if (stringRedisTemplate.hasKey(TOKEN_PREFIX + uid)) {
                String[] tmp = stringRedisTemplate.opsForValue().get(TOKEN_PREFIX + uid).split("-");

                return tmp[1];
            } else {
                return "";
            }
        } catch (NullPointerException e) {
            return "";
        }
    }

    public boolean needRefreshToken(String oldToken) {
        String uid = getTokenUId(oldToken);
        if (uid.equals("")) {
            // 无效Token
            return false;
        } else {
            String[] tmp = oldToken.split("-");
            long expireTime = Long.parseLong(tmp[2]) + Long.parseLong(tmp[3]);

            return expireTime < System.currentTimeMillis();
        }
    }

}

